package com.hao.main;

import java.util.ArrayList;

import GiaoHangVietNam.Entities.GoodsInfor;
import GiaoHangVietNam.Entities.InvoiceDetails;
import GiaoHangVietNam.RawInfor.EventCode;
import GiaoHangVietNam.RawInfor.GlobalStatus;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DetailInvoiceActivity extends Activity implements OnClickListener,
		Runnable {
	Button confirmShipBtn, confirmNotShipBtn, historyShipBtn;
	TextView nameCustomerTv, phoneNumberTv, addressCusTv, companyNameTv;
	ListView detailInvoicesLv;
	LinearLayout callCustomerLnl, googleMapLnl;
	double Lat, Lng;
	String phoneNumber, companyName, customerName;
	Boolean isSending;
	String listGoodsName;
	boolean flag = false;

	/** đánh dấu trạng thái đơn hàng (hủy hay xác nhận) */
	boolean isFinish = false;

	ArrayList<GoodsInfor> goodsInforList = new ArrayList<GoodsInfor>();
	DetailGoodInforArrayAdapter detailInvoiceAdapter;

	ProgressDialog showDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.info_detail_ship_layout);
		confirmShipBtn = (Button) findViewById(R.id.confirm_ship_btn);
		confirmShipBtn.setOnClickListener(this);
		confirmNotShipBtn = (Button) findViewById(R.id.confirm_not_ship_btn);
		confirmNotShipBtn.setOnClickListener(this);

		historyShipBtn = (Button) findViewById(R.id.history_btn);
		historyShipBtn.setOnClickListener(this);
		nameCustomerTv = (TextView) findViewById(R.id.name_customer_tv);
		companyNameTv = (TextView) findViewById(R.id.companyName_tv);
		// nameGoodTv = (TextView) findViewById(R.id.name_good_tv);
		phoneNumberTv = (TextView) findViewById(R.id.phone_number_customer_tv);
		// costShipTv = (TextView) findViewById(R.id.cost_goods_tv);
		// feeShipTv=(TextView)findViewById(R.id.cost_ship_tv);
		detailInvoicesLv = (ListView) findViewById(R.id.detail_invoices_lv);

		addressCusTv = (TextView) findViewById(R.id.address_customer_tv);
		callCustomerLnl = (LinearLayout) findViewById(R.id.call_customer_lnl);
		callCustomerLnl.setOnClickListener(this);
		googleMapLnl = (LinearLayout) findViewById(R.id.google_map_lnl);
		googleMapLnl.setOnClickListener(this);
		getPara();

	}

	private void playMusicFile() {
		// Rung chuông, file nhạc đặt trong thư mục raw trong res, có thể chơi
		// mọi đuôi nhạc, mp3,mp4...
		MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.alarm);
		mPlayer.start();
	}

	// Lấy dữ liệu từ Main
	private void getPara() {
		// Chia 2 loại bản tin

		// lấy intent gọi Activity này
		Intent callerIntent = getIntent();
		int index = callerIntent.getIntExtra("index", 1);
		Boolean isNew = callerIntent.getBooleanExtra("IsNewInvoice", false);
		if (index != 0) {
			confirmShipBtn.setEnabled(false);
			confirmNotShipBtn.setEnabled(false);

		}
		InvoiceDetails data = (InvoiceDetails) callerIntent
				.getSerializableExtra("MyPackage");
		// nameGoodTv.setText(data.GoodsName);
		addressCusTv.setText(data.Address);
		phoneNumberTv.setText(data.Number);
		nameCustomerTv.setText(data.Name);
		companyNameTv.setText(data.CompanyName);

		/** Lấy arrayList GoodsInfo ra */
		goodsInforList = data.ListGoods;
		// lấy cho vào goodsInforList
		detailInvoiceAdapter = new DetailGoodInforArrayAdapter(
				DetailInvoiceActivity.this, R.layout.detail_invoice_list_item,
				goodsInforList);
		// set vào list view
		detailInvoicesLv.setAdapter(detailInvoiceAdapter);

		Lat = data.Lat;
		Lng = data.Lng;

		phoneNumber = data.Number;
		companyName = data.CompanyName;
		customerName = data.Name;
		isSending = data.IsSending;

		for (int i = 0; i < data.ListGoods.size(); i++) {
			if (i == 0)
				listGoodsName = data.ListGoods.get(i).GoodsName;
			else
				listGoodsName += "," + data.ListGoods.get(i).GoodsName;
		}

		if (data.IsSending == true) {

			confirmShipBtn.setText("Đã giao hàng");
			confirmNotShipBtn.setText("Hủy giao hàng");
		} else {

			confirmShipBtn.setText("Đã nhận hàng");
			confirmNotShipBtn.setText("Hủy nhận hàng");
		}
		if (isNew == true) {

			// TODO Auto-generated method stub
			android.app.AlertDialog.Builder alert = new AlertDialog.Builder(
					this);
			alert.setTitle("Đơn hàng mới gần bạn hơn");
			alert.setMessage("Hãy gọi điện cho khách hàng");
			alert.setPositiveButton("OK", null);
			alert.show();
			Vibrator v = (Vibrator) this
					.getSystemService(Context.VIBRATOR_SERVICE);
			v.vibrate(500);
			playMusicFile();
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.confirm_ship_btn: {
			FinishInvoice();
			break;
		}
		case R.id.confirm_not_ship_btn:
			CancelInvoice();
			// Xác nhận chưa giao được cho khách
			break;
		case R.id.history_btn:
			if (isNetworkAvailable() == false) {
				showDialog("Thiết bị chưa kết nối internet");
			} else {
				if (GlobalStatus.IsTCPConnecting == false) {
					showDialog("Thiết bị đã mất kết nối server");
				} else
					finish();
			}
			break;
		case R.id.call_customer_lnl:
			// gọi điện thoại tới khách hàng;
			callCustomer();
			break;
		case R.id.google_map_lnl:
			// sang Activity về GoogleMap có Bundle dữ liệu là tọa độ điểm cần
			Intent intent = new Intent(this, GoogleMapActivity.class);
			intent.putExtra("Lat", Lat);
			intent.putExtra("Lng", Lng);
			intent.putExtra("Number", phoneNumber);
			intent.putExtra("CustomerName", customerName);
			intent.putExtra("CompanyName", companyName);
			intent.putExtra("IsSending", isSending);
			intent.putExtra("ListGoodsName", listGoodsName);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	// Hoàn thành đơn hàng
	public void FinishInvoice() {

		AlertDialog.Builder b = new AlertDialog.Builder(
				DetailInvoiceActivity.this);

		b.setTitle("Xác nhận chắc chắn!");
		b.setMessage("Đã giao/nhận hàng");
		b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

				isFinish = true;
				showDialog = ProgressDialog.show(DetailInvoiceActivity.this,
						"Kết nối..", "Đang chờ kết nối", true, false);
				Thread thread = new Thread(DetailInvoiceActivity.this);
				thread.start();

			}
		});
		b.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which)

			{
				dialog.cancel();
			}
		});
		b.create().show();

	}

	// Hủy đơn hàng
	private void CancelInvoice() {
		AlertDialog.Builder b = new AlertDialog.Builder(
				DetailInvoiceActivity.this);

		b.setTitle("Xác nhận chắc chắn!");
		b.setMessage("Hủy đơn hàng");
		b.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				isFinish = false;
				showDialog = ProgressDialog.show(DetailInvoiceActivity.this,
						"Kết nối..", "Đang chờ kết nối", true, false);
				Thread thread = new Thread(DetailInvoiceActivity.this);
				thread.start();
			}
		});
		b.setNegativeButton("No", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which)

			{
				dialog.cancel();
			}
		});
		b.create().show();

	}

	// Hàm gửi dữ liệu về Activity1
	public void sendToMain(int value, int resultcode) {
		Intent intent = getIntent();
		Bundle bundle = new Bundle();
		bundle.putInt("InvoiceStatus", value);
		intent.putExtra("MyPackage", bundle);
		setResult(resultcode, intent); // phương thức này sẽ trả kết quả cho
										// Activity1
		finish(); // Đóng Activity hiện tại
	}

	public void callCustomer() {

		String uri = "tel:" + phoneNumberTv.getText() + "".trim();
		Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setData(Uri.parse(uri));
		this.startActivity(intent);
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}

	// hiển thị diaglog thông báo chưa kết nối internet;
	private void showDialog(String content) {
		AlertDialog.Builder b = new AlertDialog.Builder(
				DetailInvoiceActivity.this);

		b.setTitle("Thông báo! ");
		b.setMessage(content);
		b.setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		b.create().show();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		staskBackground stask = new staskBackground();

		flag = stask.countNumber();
		handler.sendEmptyMessage(0);
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			showDialog.dismiss();
			if (flag) {
				if (isFinish) {
					sendToMain(EventCode.FINISH_INVOICE,
							MainActivity.INVOICE_STATUS);
				} else {
					sendToMain(EventCode.CANCEL_INVOICE,
							MainActivity.INVOICE_STATUS);
				}

			} else {
				Toast.makeText(getApplicationContext(), "Chưa kết nối Internet! ", Toast.LENGTH_LONG).show();
			}
		}
	};

}
